# -*- coding: utf-8 -*-

"""
Description: 商品详情转化
"""
from bs4 import BeautifulSoup
import re

# from bs4 import MarkupResemblesLocatorWarning

ald_style = """
.ls_description p {
    margin: 12px 0;
    padding: 8px 12px;
    border-radius: 4px;
    background-color: #f9f9f9;
    border-left: 4px solid #4a86e8;
}

.ls_description strong {
    color: #2c5282;
    min-width: 100px;
    display: inline-block;
}

.ls_description p:nth-child(odd) {
    background-color: #f0f4f8;
}

.ls_description p:nth-child(even) {
    background-color: #f9f9f9;
}

.ls_description p:hover {
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}
"""


def rj_imglist(input: list | str) -> list:
    """转换rj图片链接列表
    1. 长度大于5时，截取前5。否则用辰星logo图补齐长度
    2. 每一项转换为图片对象
    3. 返回处理结果

    Args:
        input (list|str): 原始图片列表

    Returns:
        list: [{"photo": url},xxxx]
    """

    logo_url = "https://images.rjmart.cn/image/enqu62up/860d4319-09b2-4af2-8cde-3bb94773fdee.jpg"

    # 处理字符串输入
    if isinstance(input, str):
        return [{"photo": input}] + [{"photo": logo_url}] * 4

    # 处理列表输入
    # 截取或补齐长度
    input = input[:5]
    if len(input) < 5:
        input.extend([logo_url] * (5 - len(input)))

    # 将url列表转换为图片对象
    return [{"photo": url} for url in input]


def add_dom_style():
    """
    description: 添加样式
    return {*}
    """
    _description = BeautifulSoup("", "html.parser")
    style_tag = _description.new_tag("style")
    # 创建样式标签
    style_tag.string = ald_style
    _description.append(style_tag)
    return _description


def create_container(soup) -> str:
    """
    description: 创建新内容详情区域
    param {*} soup
    return {*}
    """

    _description = BeautifulSoup("", "html.parser")
    div_dom = _description.new_tag("div", attrs={"class": "ls_description"})
    # div_dom.append(add_dom_style())
    div_dom.append(soup)

    return str(div_dom)


def del_old_dom(soup):
    """
    description: 删除旧DOM 结构
    param {*} soup
    return {*}
    """
    img_tags = soup.find_all("img", src=lambda x: x and x.startswith("data:image"))
    if img_tags:
        for img_tag in img_tags:
            img_tag.decompose()

    # 删除旧版广告
    old_ad_tag = soup.find("div", attrs={"id": "con_header"})
    if old_ad_tag:
        old_ad_tag.decompose()

    # 删除所有空src属性的 img 标签
    img_tags = soup.find_all("img")

    # 删除旧版咨询客服
    del_service_block = soup.find("div", attrs={"class": "cxsw_service"})
    if del_service_block:
        del_service_block.decompose()

    # 删除头部广告
    del_header = soup.find("div", attrs={"class": "cxsw_header_placeholder"})
    if del_header:
        del_header.decompose()

    # 删除尾部广告
    del_footer = soup.find("div", attrs={"class": "cxsw_footer_placeholder"})
    if del_footer:
        del_footer.decompose()

    # 删除更新信息
    check_update = soup.find("div", attrs={"class": "cxsw_updata_block"})
    if check_update:
        check_update.decompose()

    return soup


def html_processon(html_str: str) -> str:
    """
    description: 商品 HMTL 加工总方法
    param {str} html_str html 源代码
    return {str} 新商品详情
    """

    # 删除异常img 标签
    pattern = r"<img\s+src=\"\"\s*/>"
    cleaned_text = re.sub(pattern, "", html_str)

    # 解析原始商品详情
    soup = BeautifulSoup(cleaned_text, "html.parser")

    clean_soup = del_old_dom(soup)

    # 创建新 ls_description
    old_class = clean_soup.find("div", attrs={"class": "cxsw_description"})
    if old_class:
        old_class["class"] = ["ls_description"]
        # old_class.insert(0, add_dom_style())
        return str(clean_soup)
    else:
        return create_container(clean_soup)


def replace_img(old_list,pro_code:str) -> list:

    # 替换新商品主图
    base_url =f"https://ls-img-1316961827.cos.ap-guangzhou.myqcloud.com/photos/labselect/{pro_code}.png"
    old_list[0]["photo"] = base_url
    # old_url = "https://images.rjmart.cn/image/enqu62up/860d4319-09b2-4af2-8cde-3bb94773fdee.jpg"
    # 莱斯 logo
    # new_url = "https://shop-img.rjmart.cn/file/suppfloor/cacfce/25c948cd-51ce-42ef-82d5-2d6981f5c112.png"

    # # # 高效写法：列表推导式+字典解包
    # data = [
    #     {**item, "photo": new_url if item["photo"] == old_url else item["photo"]}
    #     for item in old_list
    # ]
    # return data

    return old_list
    # new_list = []
    # for _ in range(5):
    #     new_list.append(old_list[0])
    # return new_list
